package com.xzx.shop_front_api.controller;

import com.google.gson.Gson;
import com.xzx.shop_front_api.entity.Category;
import com.xzx.shop_front_api.mapper.CategoryMapper;
import com.xzx.shop_front_api.service.CategoryService;
import com.xzx.shop_front_api.utils.CategoryTreeGenerator;
import com.xzx.shop_front_api.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("add")
    public JsonResult add(@RequestBody Category category) {
        //验证分类名不能为空
        if (category.getCateName().isEmpty()) {
            return JsonResult.failed("分类名不能为空");
        }
        //验证分类名重复性
        Category cateInfo = categoryService.getCategoryByCateName(category.getCateName());
        System.out.println(cateInfo);
        if (cateInfo != null) {
            return JsonResult.failed("该分类名已存在。");
        }
        int result = categoryService.insertCategory(category);
        if (result == 0) {
            return JsonResult.failed("添加失败");
        }
        return JsonResult.success("添加成功",null);
    }
    //三级分类列表接口
    @GetMapping("categories_list")
    public JsonResult categoriesList() {
        //使用缓存
        Gson gson = new Gson();
        List<Category> treeCategories;
        String jsonTreeCategories = "";
        if (stringRedisTemplate.opsForValue().get("categories_list") == null) {
            List<Category> categoriesList = categoryService.getAllCategory();
            CategoryTreeGenerator generator = new CategoryTreeGenerator();
            treeCategories = generator.buildTree(categoriesList);
            jsonTreeCategories = gson.toJson(treeCategories);
            stringRedisTemplate.opsForValue().set("categories_list", jsonTreeCategories);
        } else {
            jsonTreeCategories = stringRedisTemplate.opsForValue().get("categories_list");
        }

        return JsonResult.success("ok", jsonTreeCategories);
    }
}
